package tk.mybatis.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.springboot.mapper.*;
import tk.mybatis.springboot.model.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by  on 2017/4/17.
 */
@Controller
@ControllerAdvice
public class CoreController {

    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/")
    public String index(){
        return "frame";
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(){
        return "login";
    }
    @RequestMapping(value = "/frame",method = RequestMethod.GET)
    public String frame(){
        return "frame";
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(String username, String password, HttpSession session){
        Users users = userMapper.selectOne(new Users() {
            {
                setUsername(username);
                setPassword(password);
            }
        });
        if(null == users){
            throw new RuntimeException("用户名或者密码错误");
        }
        session.setAttribute("me",users);
        //return new Message(users);
        return "frame";
    }
    @RequestMapping(value = "/mobile/login",method = RequestMethod.POST)
    @ResponseBody
    public Object mobileLogin(String username, String password){
        Users users = userMapper.selectOne(new Users() {
            {
                setUsername(username);
                setPassword(password);
            }
        });
        if(null == users){
            throw new RuntimeException("用户名或者密码错误");
        }
        return new Message(users);
    }

    private Users getLoginUser(HttpSession session){
        Users me = (Users)session.getAttribute("me");
        return me;
    }

    @RequestMapping(value = "/teacher",method = RequestMethod.GET)
    public String teacher(Model model){
        model.addAttribute("list",userMapper.select(new Users(){
            {
                setType("1");
            }
        }));
        return "teacher";
    }
    @RequestMapping(value = "/student",method = RequestMethod.GET)
    public String student(Model model){
        model.addAttribute("list",userMapper.select(new Users(){
            {
                setType("2");
            }
        }));
        return "student";
    }
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private FeedbackMapper feedbackMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private CourseMapper courseMapper;
    @RequestMapping(value = "/prof",method = RequestMethod.GET)
    public String prof(Model model){
        model.addAttribute("list",deptMapper.selectAll());
        return "prof";
    }
    @RequestMapping(value = "/prof",method = RequestMethod.POST)
    @ResponseBody
    public Object prof(Dept dept){
        if(null == dept.getId()){
            deptMapper.insertSelective(dept);
        }
        else {
            deptMapper.updateByPrimaryKeySelective(dept);
        }
        return new Message();
    }
    @RequestMapping(value = "/course",method = RequestMethod.GET)
    public String course(Model model){
        List<Course> courses = courseMapper.selectAll();
        for(Course course:courses){
            course.setTeacherName(userMapper.selectByPrimaryKey(course.getTeacherId()).getName());
        }
        model.addAttribute("list",courses);
        return "course";
    }
    @RequestMapping(value = "/resource",method = RequestMethod.GET)
    public String resource(Model model){
        model.addAttribute("list",resourceMapper.selectAll());
        return "resource";
    }

    @RequestMapping(value = "/resource",method = RequestMethod.POST)
    public String resource(Resource resource,@RequestParam(name = "attach1",required = false) MultipartFile file,Model model) throws Exception{
        if(!file.isEmpty()) {
            resource.setAttach(file.getBytes());
            resource.setAttachFileName(file.getOriginalFilename());
        }
        if(null == resource.getId()){
            resourceMapper.insertSelective(resource);
        }
        else{
            resourceMapper.updateByPrimaryKeySelective(resource);
        }
        model.addAttribute("msg","操作成功");
        return "500";
    }


    @RequestMapping(value = "/feedback",method = RequestMethod.GET)
    public String feedback(Model model){
        model.addAttribute("list",feedbackMapper.selectAll());
        return "feedback";
    }

    @ExceptionHandler
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Object error(Exception e){
        return new Message(e.getMessage(),null);
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public Object uploadAttach(MultipartFile file) throws Exception{

        resourceMapper.insert(new Resource(){
            {
                setType("文件上传");
                setName(file.getName());
                setAttach(file.getBytes());
            }
        });
        return new Message(null);
    }

    @RequestMapping(value="/download/{id}",method=RequestMethod.GET)
    public void download(@PathVariable int id,HttpServletResponse response) throws IOException {

        Resource resource = resourceMapper.selectByPrimaryKey(id);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + resource.getAttachFileName());

        OutputStream os = response.getOutputStream();
        os.write(resource.getAttach());

        os.close();
    }
}
